package team.southcat.wsyygh.user.controllor;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import team.southcat.wsyygh.common.result.Result;
import team.southcat.wsyygh.common.result.ResultCodeEnum;
import team.southcat.wsyygh.common.util.JwtUtil;
import team.southcat.wsyygh.common.util.MD5Util;
import team.southcat.wsyygh.model.pojo.hospital.Hospital;
import team.southcat.wsyygh.model.pojo.user.Admin;
import team.southcat.wsyygh.user.service.AdminService;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "管理员接口")
@RestController
@RequestMapping("/admin/user")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @ApiOperation("医院管理员登录")
    @PostMapping("/hospitalLogin")
    public Result login(@RequestBody Admin admin){
        //检查是否存在该管理员
        Admin selectAdmin = adminService.getByAdminName(admin.getAdminName());
        System.out.println("查询：" + selectAdmin);
        if(selectAdmin == null){
            return Result.fail().message("该管理员账户不存在");
        }
        //权限是否为1：医院管理员
        if (!"1".equals(selectAdmin.getRole())){
            return Result.fail().message("该管理员账户权限不够");
        }
        //校验密码
        if (MD5Util.encrypt(admin.getPassword()).equals(selectAdmin.getPassword())){
            //密码正确
            //生成token
            String token = JwtUtil.sign(admin.getAdminName(), selectAdmin.getId().toString());
            System.out.println("tokne已创建：" + token);
            return Result.ok(token);
        }else{
            return Result.fail().message("用户名或密码错误，请重试");
        }

    }

    //根据token获取管理员信息，供给前端路由守卫使用，每次路由变化时需要获取管理员信息
    @ApiOperation("根据token获取管理员信息")
    @GetMapping("/getInfo")
    public Result getInfo(@RequestParam("token") String token){
        System.out.println("查询管理员信息");
        //获取id
        String adminId = JwtUtil.getUserId(token);
        //查询
        Admin admin = adminService.getById(adminId);

        if(admin != null){
            Map<String, Object> adminInfo = new HashMap<>();
            adminInfo.put("name", admin.getAdminName());
            adminInfo.put("roles", admin.getRole().equals("0") ? "SystemAdmin" : "HospitalAdmin");
            adminInfo.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");  //头像
            return Result.ok(adminInfo);
        }else{
            //失败
            return Result.fail(ResultCodeEnum.FETCH_USERINFO_ERROR);
        }
    }

    @GetMapping("/getAdminById/{id}")
    public Result getAdminById(@PathVariable Integer id){
        Admin admin = adminService.getById(id);
        return Result.ok(admin);
    }

    @ApiOperation("添加医院管理员")
    @PostMapping("/addAdmin")
    public Result addAdmin(@RequestBody Admin admin){
        Result result = adminService.addAdmin(admin);
        return  result;
    }
}
